package BookManagement.controller;

import BookManagement.domain.*;
import BookManagement.service.BookService;
import BookManagement.service.BorrowService;
import BookManagement.service.CommentService;
import BookManagement.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    @Qualifier("bookService")
    private BookService bookService;

    @Autowired
    @Qualifier("borrowService")
    private BorrowService borrowService;

    @Autowired
    @Qualifier("commentService")
    private CommentService commentService;

    //跳转个人中心
    @RequestMapping("/index")
    public ModelAndView toIndex(){
        return new ModelAndView("user/indexUser");
    }

    //借书数据库操作，返回借阅信息
    private String borrow(String bookISBN,String username,int num,String length,Book book,HttpSession hs){
        int bookCounts = book.getBookCounts()-1;
        HashMap<String,Object>map=new HashMap<>();
        map.put("username",username);
        map.put("bookISBN",bookISBN);
        Borrow borrow = borrowService.searchBorrowingBook(map);
        if(borrow!=null){
            hs.setAttribute("repeat","repeat");
            return "已借阅此书";
        }
        map.put("borrowNum",++num);
        map.put("bookCounts",bookCounts);
        borrowService.borrowBook(new Borrow(bookISBN,username,book.getBookName(),length));
        userService.updateBorrowNum(username);
        bookService.updateBookCounts(map);
        return "借阅成功";
    }

    //借书
    @RequestMapping("/borrowBook")
    public ModelAndView borrowBook(String bookISBN,String length,String str,String pageNo,HttpSession hs){
        ModelAndView mav=new ModelAndView();
        mav.addObject("str",str);
        mav.addObject("pageNo",pageNo);
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        Book book = bookService.findByISBN(bookISBN);
        HashMap<String,Object>map=new HashMap<>();
        map.put("bookISBN",bookISBN);
        map.put("userName",user.getUserName());
        Borrow borrow = borrowService.searchBorrowingBook(map);
        if(borrow!=null){
            hs.setAttribute("borrowMsg","已借阅");
            mav.setViewName("user/borrowFail");
            return mav;
        }
        String credit=user.getCredit();
        String borrowMsg=new String();
        if(!credit.equals("E")){
            if(book.getBookCounts()<1){
                borrowMsg="本书已无库存";
                hs.setAttribute("borrowMsg",borrowMsg);
                mav.setViewName("user/borrowFail");
                return mav;
            }else{
                if (str==null && pageNo==null){
                    hs.setAttribute("page","details");
                } else {
                    hs.setAttribute("page","searching");
                }
                switch (credit){
                    case "D":{
                        if(user.getBorrowNum()==0){
                            borrowMsg=borrow(bookISBN, user.getUserName(), user.getBorrowNum(),length, book,hs);
                        }else{
                            borrowMsg="借阅已达上限";
                            hs.setAttribute("borrowMsg",borrowMsg);
                            mav.setViewName("user/borrowFail");
                            return mav;
                        }break;
                    }
                    case "C":{
                        if(user.getBorrowNum()<3){
                            borrowMsg=borrow(bookISBN, user.getUserName(), user.getBorrowNum(),length, book,hs);
                        }else{
                            borrowMsg="借阅已达上限";
                            hs.setAttribute("borrowMsg",borrowMsg);
                            mav.setViewName("user/borrowFail");
                            return mav;
                        }break;
                    }
                    case "B":{
                        if(user.getBorrowNum()<5){
                            borrowMsg=borrow(bookISBN, user.getUserName(), user.getBorrowNum(),length, book,hs);
                        }else{
                            borrowMsg="借阅已达上限";
                            hs.setAttribute("borrowMsg",borrowMsg);
                            mav.setViewName("user/borrowFail");
                            return mav;
                        }break;
                    }
                    case "A":{
                        if(user.getBorrowNum()<10){
                            borrowMsg=borrow(bookISBN, user.getUserName(), user.getBorrowNum(),length, book,hs);
                        }else{
                            borrowMsg="借阅已达上限";
                            hs.setAttribute("borrowMsg",borrowMsg);
                            mav.setViewName("user/borrowFail");
                            return mav;
                        }break;
                    }
                }
            }
        }else{
            borrowMsg="信用不足，请升级信用";
            hs.setAttribute("borrowMsg",borrowMsg);
            mav.setViewName("user/borrowFail");
            return mav;
        }
        hs.setAttribute("borrowMsg",borrowMsg);
        mav.setViewName("user/borrowSuccessfully");
        return mav;
    }

    //还书
    @RequestMapping("/backBook")
    public ModelAndView backBook(String bookISBN,HttpSession hs) throws ParseException {
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){//未登录，跳转至登录界面
            mav.setViewName("/account/indexLogin");
            return mav;
        }
        Book book=bookService.findByISBN(bookISBN);
        HashMap<String,Object>map=new HashMap<>();
        int bookCounts=book.getBookCounts()+1;
        map.put("bookISBN",bookISBN);
        map.put("userName",user.getUserName());
        map.put("bookCounts",bookCounts);
        Borrow borrow = borrowService.searchBorrowingBook(map);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String now=df.format(new Date());
        String length=new Borrow().getTime(df.parse(now),df.parse(borrow.getTimeStart()),borrow.getLength());
        String credit=user.getCredit();
        String tmp=new String();
        if(Integer.valueOf(length.substring(0,length.length()-1))<0){//未按期归还，降低信用
            switch (credit){
                case "D":{
                    user.setCredit("E");
                    tmp="超出还书期限，信用等级由D降为E！";
                    break;
                }
                case "C":{
                    user.setCredit("D");
                    tmp="超出还书期限，信用等级由C降为D！";
                    break;
                }
                case "B":{
                    user.setCredit("C");
                    tmp="超出还书期限，信用等级由B降为C！";
                    break;
                }
                case "A":{
                    user.setCredit("B");
                    tmp="超出还书期限，信用等级由A降为B！";
                    break;
                }
            }
        }
        else {
            user.setPoint(user.getPoint()+10);
            tmp="按时归还，积分加10";
        }
        user.setBorrowNum(user.getBorrowNum()-1);
        book.setBookCounts(bookCounts);
        userService.updateUser(user);
        borrowService.backBook(map);
        bookService.updateBookCounts(map);
        hs.setAttribute("backMsg","还书成功，"+tmp);
        mav.setViewName("user/backSuccessfully");
        return mav;
    };

    //查看用户借书
    @RequestMapping("/showBorrowByUser")
    public ModelAndView showBorrowByUser(HttpSession hs) throws ParseException {
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        HashMap<String,Object>map=new HashMap<>();
        map.put("username",user.getUserName());
        List<Borrow> borrowList = borrowService.searchAllBorrowingBookWithUsername(map);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String now = df.format(new Date());
        for (int i=0; i<borrowList.size(); i++){
            String length = new Borrow().getTime(df.parse(now),df.parse(borrowList.get(i).getTimeStart()),borrowList.get(i).getLength());
            length = length.substring(0,length.length()-1);
            if (Integer.valueOf(length) < 0){
                length = "超时 "+length.substring(1)+" 天";
            } else {
                length = "还剩 "+length+" 天";
            }
            borrowList.get(i).setLength(length);
        }
        mav.addObject("borrowList",borrowList);
        mav.addObject("username",user.getName());
        mav.setViewName("/user/allBorrowOfUser");
        return mav;
    }




    //读取用户头像
    @RequestMapping("/readPhoto")
    public void readPhoto(String username,HttpServletResponse response, HttpSession hs){
        try{
            User user =userService.findUserByUsername(username);
            FileInputStream fis=new FileInputStream(hs.getServletContext().getRealPath(user.getPhoto()));
            byte[] d=new byte[fis.available()];
            fis.read(d);
            fis.close();
            response.setContentType("img/*");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(d);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //升级信用
    @RequestMapping("/updateCredit")
    public ModelAndView updateCredit(HttpSession hs){
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        ModelAndView mav=new ModelAndView();
        String updateCreditMsg=new String();
        int point=user.getPoint();
        if(point<100){
            updateCreditMsg="积分不足！";
            hs.setAttribute("updateCreditMsg",updateCreditMsg);
            return new ModelAndView("/user/updateCredit");
        }
        String credit = user.getCredit();
        if(credit.equals("A")){
            updateCreditMsg="已到最高级！";
            hs.setAttribute("updateCreditMsg",updateCreditMsg);
            return new ModelAndView("/user/updateCredit");
        }
        point-=100;
        switch (credit){
            case "E":{
                credit="D";
                updateCreditMsg="升级完毕！";
                break;
            }
            case "D":{
                credit="C";
                updateCreditMsg="升级完毕！";
                break;
            }
            case "C":{
                credit="B";
                updateCreditMsg="升级完毕！";
                break;
            }
            case "B":{
                credit="A";
                updateCreditMsg="升级完毕！";
                break;
            }
        }
        user.setPoint(point);
        user.setCredit(credit);
        userService.updateUser(user);
        hs.setAttribute("updateCreditMsg",updateCreditMsg);
        mav.setViewName("/user/updateCredit");
        return mav;
    }
}
